
/**
 * Created by wangjiakun on 2018/4/4 0004.
 */
import React from 'react';
import { connect } from 'react-redux';

import { messages, getApprovelHistory } from 'share/common';
import {Input,InputNumber, Form, Tabs, Button, Spin, Radio, Card, Row, Col, message, DatePicker, Affix,Select, Popover, Divider} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const TabPane = Tabs.TabPane;

import moment from 'moment';
import debounce from 'lodash.debounce'
import travelService from 'containers/request/travel-request/travel.service'
import travelUtil from 'containers/request/travel-request/travelUtil'
import TravelLocation from 'containers/request/travel-request/comp/location'
import TravelPrompt from 'containers/request/travel-request/travel-prompt'

class TravelHotel extends React.Component{

  supply = {};
  searchType = "standard";
  intEnable = true;//是否可选到国际
  clearHistory = false;//是否切换供应商的时候直接清空地址
  startDate = "";
  endDate = "";
  baseStartDate = "";
  baseEndDate = "";
  dateArray = [];//盛放已选过的酒店日期
  out_participant_num = 0;//外部参与人数
  select_participant = [];//参与人
  constructor(props){
    super(props);
    this.state = {
      params:{},//接收父组件带来的参数
      editing:false,//区分编辑页还是新建页
      formCtrl:{},//
      standardEnable:false,//是否走差旅标准
      promptList: [], //行程提示语的配置
      duplicateEnable: false, //是否允许重复的酒店日期
      supplies: [],//所有供应商
      currentIndex: 0,//当前供应商数组的下标
      supplyId:'',//当前供应商serviceName
      defaultDate:""+moment(travelUtil.getDefaultDate(1)).format('YYYY-MM-DD'),
      isLoading: false,//提交是否loading提示
      citySearchResult:[],//城市搜索结果
      maxRoom:1,//最大房间数
      minPrice:0,//最小价格
      selectCity:{},//选择的住宿城市
      nights:0,//住宿晚间数
    };
  }

  //初始化编辑数据
  componentWillReceiveProps(){
    let hotelRecord = [];
    if(this.props.params.isResetHotel){
      this.resetForm();
      delete this.props.params.isResetHotel;
      return;
    }
    let editData = travelUtil.isEmpty(this.props.params.editHotel);
    let TAG =  editData.isEmpty;
    if(!TAG){
      if(!this.state.editing){
        let num = 0;
        let supId = 0;
        this.state.supplies.map((item,index)=>{
          if(item.supplierOID==editData.supplierOID){
            num = index;
            supId = item.supplierServiceName;
            this.supply = item;
            if (this.supply.function && this.supply.function[0]) {
              this.searchType = 'standard';//this.supply.function[0].locationVendorType;
              this.intEnable = this.supply.function[0].intEnable;
            } else {
              this.searchType = 'standard';
              this.intEnable = true;
            }
          }
        });
        this.updateMaxRoom();//更新最大房间数
        let night = travelUtil.calculateDate(editData.fromDate, editData.leaveDate) - 1;
        this.setState({
          editing:true,
          currentIndex:num,
          supplyId:supId,
          nights:night,
          selectCity:editData.cityName?{code:editData.cityCode,vendorAlias:editData.cityName}:{},
        },()=>{
          this.props.form.resetFields();
        })
      }
      this.props.params.hotel.map(h =>{
        if(h.hotelItineraryOID !== editData.hotelItineraryOID){
          hotelRecord.push(h);
        }
      });
      this.dateArray = travelUtil.hotelDateArray(hotelRecord);
    }else {
      if(this.props.params.hotel){
        this.dateArray = travelUtil.hotelDateArray(this.props.params.hotel);
      };
      let tempStartDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'start_date');
      let tempEndDate = travelUtil.getFormHeadValue(this.props.params.defaultValue, 'end_date');
      let outNum = travelUtil.getFormHeadValue(this.props.params.defaultValue,'out_participant_num');
      let select_participant = [];
      select_participant = travelUtil.getFormHeadValue(this.props.params.defaultValue,'select_participant');
      if(this.baseStartDate !== tempStartDate || this.baseEndDate !== tempEndDate ||
        this.out_participant_num !== outNum || this.select_participant !== JSON.stringify(select_participant)){//头部时间、参与人、外部参与人数是否已经改变
        this.setThisDate();
        this.updateMaxRoom();//更新最大房间数
      }
    }
    this.setState({minPrice:this.props.form.getFieldValue('minPrice')});
  }

  //设置日期
  setThisDate = () =>{
    this.startDate = travelUtil.getFormHeadValue(this.props.params.defaultValue,'start_date');
    this.endDate = travelUtil.getFormHeadValue(this.props.params.defaultValue,'end_date');
    this.baseStartDate = travelUtil.getFormHeadValue(this.props.params.defaultValue,'start_date');
    this.baseEndDate = travelUtil.getFormHeadValue(this.props.params.defaultValue,'end_date');
    this.out_participant_num = travelUtil.getFormHeadValue(this.props.params.defaultValue,'out_participant_num');
    this.select_participant = JSON.stringify(travelUtil.getFormHeadValue(this.props.params.defaultValue,'select_participant'));
  }

  componentWillMount(){
    const { params } = this.props;
    this.getSupplies();
    let tempMap = params['travelInfo']['customFormPropertyMap'];
    let obj = tempMap['application.property.control.fields.hotel'] ? JSON.parse(tempMap['application.property.control.fields.hotel']) : travelUtil.getSetDataByTravelType('hotel');
    let isStandard = tempMap['ca.travel.applypolicy.enable'] ? JSON.parse(tempMap['ca.travel.applypolicy.enable']) : false;
    let promptList = tempMap['travel.itinerary.tips'] ? JSON.parse(tempMap['travel.itinerary.tips']) : [];
    let duplicateEnable = tempMap['hotel.repetition.control'] === 'true';
    this.updateMaxRoom();
    this.setThisDate();
    let night = travelUtil.calculateDate(this.baseStartDate, this.baseEndDate) - 1;
    this.setState({
      promptList,
      duplicateEnable,
      params,
      formCtrl:obj,
      standardEnable:isStandard,
      nights:night
    });
  }

  //时间改变重新计算日期区间天数
   startDateChange = (e) => {
    const { form } = this.props;
    let endDate = form.getFieldValue('leaveDate');
    this.startDate = e;
    let days = 0;
    days = travelUtil.calculateDate(e, endDate);
    this.setState({nights: days - 1});
  }

  //时间改变重新计算日期区间天数
  endDateChange = (e) => {
    const { form } = this.props;
    let startDate = form.getFieldValue('fromDate');
    this.endDate = e;
    let days = 0;
    days = travelUtil.calculateDate(startDate, e);
    this.setState({nights: days - 1});
  }

  updateMaxRoom = () =>{
    let outNum = travelUtil.getFormHeadValue(this.props.params.defaultValue,'out_participant_num');
    let select_participant = [];
    select_participant = travelUtil.getFormHeadValue(this.props.params.defaultValue,'select_participant');
    const formHeadMaxNum = travelUtil.getFormHeadValueByCode(this.props.params.defaultValue,'maxnum');
    if (formHeadMaxNum && typeof formHeadMaxNum === 'string') {
      console.log(this.props.params);
      this.setState({
        maxRoom: formHeadMaxNum
      });
    } else {
      travelService.getMaxRoom(outNum,select_participant).then(res=>{
        res.data.maxRoomNumber && this.setState({
          maxRoom:res.data.maxRoomNumber,
        })
      }).catch(err=>{
        message.error(err.response.data.message);
      })
    };
  }

  cfo = travelUtil.createFormOption;

  //清空已选城市数据
  clearCityData = () => {
    this.setState({
      citySearchResult: [],
      selectCity:{}
    });
    this.props.form.setFieldsValue({cityName: ""});
  };

  //选择供应商
  selectSupply = (index) => {
    this.supply = this.state.supplies[index];
    if (this.supply.function && this.supply.function[0]) {
      this.searchType = 'standard';//this.supply.function[0].locationVendorType;
      this.intEnable = this.supply.function[0].intEnable;
      this.clearHistory = this.supply.function[0].clearHistory;
    } else {
      this.searchType = 'standard';
      this.intEnable = true;
      this.clearHistory = false;
    }
    let country = 'all';
    if (!this.intEnable) {
      country = 'china';
    }
    if (this.state.selectCity.code && !this.clearHistory) {
      travelService.isCityInVendor(this.searchType, this.state.selectCity.code, country).then(res => {
        if(res.data && res.data.alias){
          //this.state.selectCity上的vendorType这个字段是上一个供应商，现在没有用到这个字段，需要注意
          this.setState({
            citySearchResult: [this.state.selectCity]
          });
        } else {
          this.clearCityData();
        }
      }).catch(err=>{
        this.clearCityData();
      });
    } else {
      this.clearCityData();
    }
    //citySearchResult:[]这还不能直接置空，不然已选中的在select中匹配不上
    this.setState({currentIndex: index,supplyId:this.supply.serviceName});
  }

  //提交
  toSubmit = (e) => {
    const { duplicateEnable } = this.state;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err,values)=>{
      if(values.remark && values.remark.length === 201){
        message.error(messages('request.key349'/*备注长度超出*/));
        return;
      }
      if(!err){
        values.supplierOID = this.supply.supplierOID ? this.supply.supplierOID : null;
        values.fromDate = moment(moment(values.fromDate).format('YYYY-MM-DD')).utc().format();//置为零点零分
        values.leaveDate = moment(moment(values.leaveDate).format('YYYY-MM-DD')).utc().format();//置为零点零分
        if(values.fromDate > values.leaveDate){
          message.error(messages('request.key350'/*退房日期不能小于入住日期*/));
          return;
        }
        if(values.fromDate === values.leaveDate){
          message.error(messages('request.key351'/*退房日期不能等于入住日期*/));
          return;
        }
        if(this.state.formCtrl.city.required && !this.state.selectCity.code){
          message.error(messages('request.key352'/*城市不匹配或未点击选择*/));
          return ;
        }
        values.cityCode = this.state.selectCity.code?this.state.selectCity.code:null;
        values.cityName = this.state.selectCity.code?this.state.selectCity.vendorAlias:null;
        //wjk add 18 05 22 判断是否跨选日期
        let isRepeatDate = travelUtil.hotelIsRepeatDate(values, duplicateEnable ? [] : this.dateArray);
        if(isRepeatDate.isRepeat){
          message.error(messages('request.key469',{arg1: isRepeatDate.dateStr}/*{arg1}已预订*/));
          return;
        }
        this.setState({isLoading:true});
        if(!this.state.editing){
          travelService.travelHotelSubmit(this.state.params.oid,[values]).then(res =>{
            this.submitFinish(messages('request.key189'/*已保存*/));
          }).catch(err=>{
            message.error(err.response.data.message);
            this.setState({isLoading:false});
          });
        }else{
          values.applicationOID = this.state.params.oid;
          values.hotelItineraryOID = this.props.params.editHotel.hotelItineraryOID;
          travelService.updateHotel(values).then(res=>{
            this.submitFinish(messages('request.key353'/*已更新*/))
          }).catch(err=>{
            message.error(err.response.data.message);
            this.setState({isLoading:false});
          })
        }
      }
    })
  }

  //提交成功提示
  submitFinish = (mes) =>{
    this.setState({isLoading:false});
    message.success(mes);
    this.props.form.resetFields();
    this.closeSlide();
  }

  //获取供应商数据
  getSupplies = () =>{
    travelService.travelSuppliers(2003).then(res=>{
      if(res['data']['2003']){
        let defaultIndex = 0;
        res['data']['2003'].map((item, index) => {
          if (item.userDefault) {
            defaultIndex = index;
          }
        });
        this.setState({
          supplies:res['data']['2003'],
          supplyId:res['data']['2003'].length > 0 ? res['data']['2003'][defaultIndex].serviceName : "",
          currentIndex: defaultIndex
        },() => {
          this.supply = this.state.supplies.length > 0 ? this.state.supplies[defaultIndex] : {};
          if (this.supply.function && this.supply.function[0]) {
            this.searchType = 'standard';//this.supply.function[0].locationVendorType;
            this.intEnable = this.supply.function[0].intEnable;
          }
        });
      }
    }).catch(err=>{
      message.error(err.response.data.message);
    });
  }

  //重置表单
  resetForm = () =>{
    this.props.form.resetFields();
    delete this.props.params.editHotel;
    let night = travelUtil.calculateDate(this.baseStartDate, this.baseEndDate) - 1;
    this.setThisDate();
    this.setState({
      editing:false,
      nights:night,
    });
  }

  // 关闭侧滑
  closeSlide = () =>{
    this.props.close();
  };

  selectCity = (cityObj) =>{
    this.setState({selectCity: cityObj});
  };

  disabledDateStart = (current) => {
    const { duplicateEnable } = this.state;
    let floatLeaveDay =  this.state.formCtrl.leaveDate.floatDays;
    let floatStartDay =  -this.state.formCtrl.fromDate.floatDays;
    return travelUtil.disabledDate(current, this.baseStartDate, this.baseEndDate, floatLeaveDay, floatStartDay, duplicateEnable ? undefined : this.dateArray) ;
  };

  disabledDateEnd = (current) => {
    const { duplicateEnable } = this.state;
    let floatLeaveDay =  this.state.formCtrl.leaveDate.floatDays + 1;
    let floatStartDay =  -this.state.formCtrl.fromDate.floatDays + 1;
    return travelUtil.disabledDate(current, this.baseStartDate, this.baseEndDate, floatLeaveDay, floatStartDay, duplicateEnable ? undefined : this.dateArray) ;
  };

  render(){
    const {formCtrl, maxRoom, minPrice, standardEnable, supplies, defaultDate, supplyId, currentIndex, isLoading,
      citySearchResult, nights, promptList} = this.state;
    const {travelInfo: {formCode}} = this.props.params;
    const {getFieldDecorator} = this.props.form;
    let editData = travelUtil.isEmpty(this.props.params.editHotel);
    let TAG =  editData.isEmpty;
    const formItemLayout = {
      labelCol: {span: 10},
      wrapperCol: {span: 12}
    }
    const formSupplyLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 18}
    }
    const formLayout = {
      labelCol: {span: 8},
      wrapperCol: {span: 12}
    }
    return (
      <div className="travel-hotel">
        <TravelPrompt promptList={promptList} type={1003} />
        <Spin spinning={isLoading}>
          <Form>
            <FormItem {...formSupplyLayout} label={messages('request.key354'/*消费商*/)} style={{display: 'none'}}>
              <Row className="supplyRow">
                {
                  supplies.map((sup, index)=> {
                    return (
                      <Col key={sup.supplyId} span={4} className="supply" onClick={()=>this.selectSupply(index)}>
                        <Card hoverable
                              className={index==currentIndex?'card-on':'card-off'}
                              cover={sup.vendorIcon ? <img src={sup.vendorIcon.path}/> : null}>
                          <Popover content={sup.name}>
                            <span className="card-name">{sup.name}</span>
                          </Popover>
                        </Card>
                      </Col>
                    )
                  })
                }
              </Row>
            </FormItem>
            <Divider style={{display: 'none'}}/>
            <Row>
              {
                (formCtrl.city.enable || formCtrl.city.show) &&  <Col span={12}>
                  <FormItem {...formLayout} label={messages('request.key357'/*入住城市*/)}>
                    {getFieldDecorator('cityName',this.cfo(messages('request.key357'/*入住城市*/),{type:'str',value:editData.cityName},!formCtrl.city.required))(
                      <TravelLocation intEnable={this.intEnable}
                                      vendorType={this.searchType}
                                      isEntity={false}
                                      formCode={formCode}
                                      onSelect={this.selectCity}
                                      isOldDataType={true}/>
                    )}
                  </FormItem>
                </Col>
              }
              {
                (formCtrl.roomNumber.enable || formCtrl.roomNumber.show) &&  <Col span={12}>
                  <FormItem  {...formLayout} label={messages('request.key359'/*最大房间数*/)}>
                    {getFieldDecorator('roomNumber',this.cfo(messages('request.key359'/*最大房间数*/),{type:'number',value:maxRoom},!formCtrl.roomNumber.required))
                    (<InputNumber disabled={true} className="plane-price"/>)}
                  </FormItem>
                </Col>
              }
            </Row>

            <Row>
              {
                (formCtrl.fromDate.enable || formCtrl.fromDate.show) && <Col span={12}>
                  <FormItem {...formLayout} label={messages('request.key360'/*入住日期*/)}>
                    {getFieldDecorator('fromDate',this.cfo(messages('request.key360'/*入住日期*/),{type:'moment',value:editData.isEmpty?this.baseStartDate:editData.fromDate},!formCtrl.fromDate.required))(
                      <DatePicker onChange={this.startDateChange} disabledDate={this.disabledDateStart}></DatePicker>
                    )}
                  </FormItem>
                </Col>
              }
              <div className="night">{messages('request.key470',{arg1:nights}/*{arg1}晚*/)}</div>
              {
                (formCtrl.leaveDate.enable || formCtrl.leaveDate.show) &&  <Col span={12}>
                  <FormItem {...formLayout} label={messages('request.key361'/*退房日期*/)}>
                    {getFieldDecorator('leaveDate',this.cfo(messages('request.key361'/*退房日期*/),{type:'moment',value:editData.isEmpty?this.baseEndDate:editData.leaveDate},!formCtrl.leaveDate.required))(
                      <DatePicker onChange={this.endDateChange} disabledDate={this.disabledDateEnd}></DatePicker>
                    )}
                  </FormItem>
                </Col>
              }
            </Row>

            {
              !standardEnable && <Row>
                {
                  formCtrl.minPrice.show &&  <Col span={12}>
                    <FormItem {...formLayout} label={messages('request.key362'/*最小价格*/)}>
                      {getFieldDecorator('minPrice',this.cfo(messages('request.key362'/*最小价格*/),{type:'number',value:editData.minPrice},!formCtrl.minPrice.required))(
                        <InputNumber min={0}></InputNumber>
                      )}
                    </FormItem>
                  </Col>
                }
                {
                  formCtrl.maxPrice.show && <Col span={12}>
                    <FormItem {...formLayout} label={messages('request.key363'/*最大价格*/)}>
                      {getFieldDecorator('maxPrice',this.cfo(messages('request.key363'/*最大价格*/),{type:'number',value:editData.maxPrice},!formCtrl.maxPrice.required))(
                        <InputNumber min={minPrice} className="maxPrice"/>
                      )}
                    </FormItem>
                  </Col>
                }
              </Row>
            }

            <FormItem label={messages('request.key364'/*备注*/)} {...formSupplyLayout}>
              {getFieldDecorator('remark', {
                rules: [{
                  required: formCtrl.remark && formCtrl.remark.required,
                  message: messages('request.key472', {arg1: messages('request.key364'/*备注*/)}/*{arg1}不能为空*/)
                }],
                initialValue: editData.remark
              })(
                <TextArea maxLength="200" placeholder={messages('request.key372'/*请输入*/)} />
              )}
            </FormItem>
          </Form>
        </Spin>
        <Affix className="travel-affix" offsetBottom={0}>
          <Button onClick={this.toSubmit} type="primary" loading={isLoading}>{messages('request.key211'/*确定*/)}</Button>
          <Button className="travel-type-btn" onClick={this.closeSlide} >{messages('request.key175'/*取消*/)}</Button>
        </Affix>
      </div>
    )
  }



}

function mapStateToProps(state) {
  return { language: state.main.language };
}

const wrappedTravelHotel = Form.create()(TravelHotel);

export default connect(mapStateToProps)(wrappedTravelHotel);
